# 邮箱验证码服务
import logging
import smtplib
from email.utils import formataddr
from email.mime.text import MIMEText
from django.conf import settings


class EmailCode:
    def __init__(self, email):
        self.receivers = email

        self.sender = settings.EMAIL_HOST_USER
        self.pwd = settings.EMAIL_HOST_PASSWORD
        self.host = settings.EMAIL_HOST
        self.port = settings.EMAIL_PORT
        self.from_ = settings.EMAIL_FROM

    def send(self, message):
        """
        发送
        :return:
        """
        server = smtplib.SMTP_SSL(self.host, self.port)  # 发件人邮箱中的SMTP服务器
        server.login(self.sender, self.pwd)
        server.sendmail(self.sender, [self.receivers, ], message.as_string())
        server.quit()  # 关闭连接

    def send_Email_code(self, code):
        """
        发送验证码信息至邮箱
        :param code: 验证码
        :return:
        """
        context = f"""
            <p>验证码: {code}</p>
        """
        message = MIMEText(context, 'html', 'utf-8')
        message['Subject'] = f"美多商城邮箱验证"  # 标题
        message['From'] = formataddr(['美多商城邮箱验证', self.sender])
        message['To'] = formataddr([self.receivers, self.receivers])

        return self.send(message)

    def send_verify_email(self, verify_url):
        """
        邮箱验证
        :param verify_url:
        :return:
        """
        context = f"""
            <p>尊敬的用户你好！</p>
            <p>感谢您使用美多商城。</p>
            <p>您的邮箱为{self.receivers}。请点击此链接激活你的邮箱：</p>
            <p><a href="{verify_url}">{verify_url}</a></p>
        """
        message = MIMEText(context, 'html', 'utf-8')
        message['Subject'] = f"美多商城邮箱验证"  # 标题
        message['From'] = formataddr(['美多商城邮箱验证', self.sender])
        message['To'] = formataddr([self.receivers, self.receivers])

        return self.send(message)